/**
 * 
 */
package zhoujian.oj.leetcode;

import org.junit.Test;

/**
 * @author hyper
 * @email zjkermit@gmail.com
 * @date Dec 19, 2013
 * @version 1.0
 * @description 
 * 		Implement atoi to convert a string to an integer.
 * 
 * 		Hint: Carefully consider all possible input cases. 
 * 			  If you want a challenge, please do not see below and 
 * 			  ask yourself what are the possible input cases.
 * 
 * 		Notes: It is intended for this problem to be specified vaguely 
 * 			   (ie, no given input specs). You are responsible to gather 
 * 			   all the input requirements up front.
 */
public class StringToInteger {
	
	public int atoi(String s) {
		long num = 0l;
		int sign = 1;
		int len = s.length();
		int i = 0;
		
		while (i < len && s.charAt(i) == ' ') i++;
		
		if (i < len && s.charAt(i) == '+') i++;
		else if (i < len && s.charAt(i) == '-') {
			sign = -1;
			i++;
		}
		
		for (; i < len; i++) {
			if (s.charAt(i) < '0' || s.charAt(i) > '9')
				break;
			num = num * 10 + s.charAt(i) - '0';
			if (num > Integer.MAX_VALUE)
				return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
		}
		
		return (int) num * sign;
	}
	
	@Test 
	public void testAtoi() {
		System.out.println(atoi("  -0012a42"));
		System.out.println(atoi("2147483648"));
		assert atoi("2134") == 2134;
		assert atoi("-2134") == -2134;
		assert atoi("-21 34") == -21;
		assert atoi("++i") == 0;
	}

}
